<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="30%" :title="`${drawerProps.title}试卷`">
    <el-form
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.title === '查看'"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="期限（月）" prop="expire_month">
        <el-input v-model="drawerProps.row!.expire_month" placeholder="请填写数字" clearable></el-input>
      </el-form-item>
      <el-descriptions title="【科目列表】📚" :column="1" border style="text-align: center"> </el-descriptions>
      <TreeFilter
        id="course_id"
        ref="courseTreeFilter"
        label="title"
        title="科目列表(单选)"
        :request-api="getCourseTreeListApi"
        @change="changeTreeFilter"
        :api-params="drawerProps.course_id"
        :default-value="selected_course_id"
        :expand-on-click-node="true"
        :show-all-tag="false"
        :default-expand-all="false"
        style="width: 100%"
      />
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleSubmit"> 提交 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="editUserCourseDrawer">
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { getCourseTreeListApi } from "@/api/modules/course";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { addUserCourseApi } from "@/api/modules/user_course";
const courseTreeFilter = ref<InstanceType<typeof TreeFilter>>();

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<any>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  course_id?: string;
  parent_id?: string;
  order_number?: string;
}

const drawerProps = ref<any>({
  isView: false,
  title: "",
  row: {},
  user_id: ""
});

const drawerVisible = ref(false);

const rules = reactive({
  name: [{ required: true, message: "请填写试卷名称" }]
});

// 接收父组件传过来的参数
const acceptParams = (params: any) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

const selected_course_id = ref<number>(0);
const changeTreeFilter = (val: string) => {
  ElMessage.success(`你选择了 id 为 ${val} 的数据🤔`);
  selected_course_id.value = Number(val);
};

// 提交数据（新增/编辑）
const handleSubmit = async () => {
  try {
    const params = {
      course_id: selected_course_id.value,
      user_id: drawerProps.value.user_id
    };
    const data = await drawerProps.value.api!(params);
    if (data.code !== "") {
      ElMessage.error(data.msg);
      return;
    }
    ElMessage.success({ message: `提交成功！` });
    drawerProps.value.getTableList!();
    drawerVisible.value = false;
  } catch (error) {
    console.log(error);
  }
  return true;
};

defineExpose({
  acceptParams
});
</script>
<style scoped lang="scss">
@import "userEditor";
</style>
